import { useMemo } from 'react';
import { MinusCircleOutlined, PlusOutlined } from '@ant-design/icons';
import { Button, Form, Select } from 'antd';
import { IS_SUBAPP, useDrsState } from 'umi';

import { differenceBy } from '@szzj/utils';
import { DeptTreeSelect } from '@szzj/drs-components';

import useDataPerm from '@/hooks/useDataPerm';
import hooks from '../../hooks';

import type { IRoleItem } from '@/types/permission/user';

export default () => {
  const { userInfo } = useDrsState();
  const { hasMenuAuthed } = useDataPerm(userInfo);
  const {
    editHooks: { editForm, deptRoleRequests },
    roleReq: { data: roleList = [] },
    roleAuthedReq: { data: roleListAuthed = [] },
    drsAppCode,
  } = hooks.useContainer();

  const realRoleAuthedList = useMemo(() => {
    const diff: IRoleItem[] = differenceBy(roleList, roleListAuthed, 'roleCode') || [];
    return roleListAuthed.concat(
      diff.map((item) => ({
        ...item,
        disabled: true,
      })),
    );
  }, [roleList, roleListAuthed]);

  return (
    <>
      <Form.List name="authList">
        {(fields, { add, remove }) => (
          <>
            {fields.map((field, index) => (
              <div
                key={field.key}
                style={{
                  border: '1px solid #eee',
                  padding: '0 20px',
                  marginBottom: 20,
                  backgroundColor: '#fbfbfb',
                }}
              >
                <Form.Item noStyle shouldUpdate>
                  {({ getFieldValue }) => {
                    const { deletedIndex } = getFieldValue('authList')?.[index] ?? {
                      deletedIndex: true,
                    };
                    const { deptCode } = getFieldValue('authList')?.[index] ?? {};
                    const found = deptRoleRequests.find((it) => it.deptCode === deptCode);
                    const disabled = !!deptCode && found && !found?.hasPermFlag;
                    return (
                      <div style={{ textAlign: 'right', padding: '10px 0' }}>
                        {deletedIndex && !disabled ? (
                          <MinusCircleOutlined
                            onClick={() => {
                              editForm.validateFields(['authList']);
                              remove(field.name);
                            }}
                          />
                        ) : (
                          <i style={{ display: 'inline-block', width: '14px', height: '14px' }}></i>
                        )}
                      </div>
                    );
                  }}
                </Form.Item>
                <Form.Item noStyle shouldUpdate>
                  {({ getFieldValue }) => {
                    const { deptCode } = getFieldValue('authList')?.[index] ?? {};
                    const found = deptRoleRequests.find((it) => it.deptCode === deptCode);
                    const disabled = !!deptCode && found && !found?.hasPermFlag;
                    const orgDisabled = !!deptCode && found && !found?.changeDept;

                    /** 若无编辑权限，手动以下拉框展示 */
                    return disabled || orgDisabled ? (
                      <Form.Item label="部门" name={[field.name, 'deptCode']}>
                        <Select
                          disabled={disabled || orgDisabled}
                          options={[{ label: found?.deptName, value: found?.deptCode }]}
                        />
                      </Form.Item>
                    ) : (
                      <Form.Item
                        label="部门"
                        name={[field.name, 'deptCode']}
                        rules={[
                          { required: true, message: '请选择' },
                          {
                            validator: (_, value) => {
                              const authList = editForm.getFieldValue('authList');
                              if (
                                value &&
                                authList.filter(
                                  (item: { deptCode: string }) => item?.deptCode === value,
                                ).length > 1
                              ) {
                                return Promise.reject('当前部门存在多个授权配置，请检查');
                              }
                              return Promise.resolve();
                            },
                          },
                        ]}
                      >
                        <DeptTreeSelect
                          customDetailRequestUrl="/user/account/dept/detail"
                          initDeptDeep={2}
                          authed={hasMenuAuthed('/permission/user')}
                          drsAppCode={drsAppCode}
                          placement="bottomRight"
                          isSubApp={IS_SUBAPP}
                        />
                      </Form.Item>
                    );
                  }}
                </Form.Item>
                <Form.Item noStyle shouldUpdate>
                  {({ getFieldValue }) => {
                    const { deptCode } = getFieldValue('authList')?.[index] ?? {};
                    const found = deptRoleRequests.find((it) => it.deptCode === deptCode);
                    const disabled = !!deptCode && found && !found?.hasPermFlag;

                    return (
                      <Form.Item
                        label="角色"
                        name={[field.name, 'roleList']}
                        rules={[{ required: true, message: '请选择' }]}
                      >
                        <Select
                          placeholder="请选择角色"
                          options={realRoleAuthedList}
                          mode="multiple"
                          fieldNames={{
                            value: 'roleCode',
                            label: 'roleName',
                          }}
                          disabled={disabled}
                        />
                      </Form.Item>
                    );
                  }}
                </Form.Item>
              </div>
            ))}
            <Button type="dashed" onClick={() => add()} block icon={<PlusOutlined />}>
              新增授权
            </Button>
          </>
        )}
      </Form.List>
    </>
  );
};
